<?php

namespace app\api\controller\notify;

use app\logic\single\group\GroupOrderSingle;
use app\logic\single\OrderEntitySingle;
use app\logic\single\OrderMusicSingle;
use app\logic\single\OrderVipSingle;
use app\logic\single\pay\WxPaySingle;
use app\Request;
use EasyWeChat\Kernel\Exceptions\Exception;
use think\facade\Log;

class Wx
{

    function __construct(Request $request)
    {
        $this->request = $request;
    }
    function index(){
        Log::write($this->request->param(),'wx-pay-notify');
        $app = WxPaySingle::getInstance()->getApp();
        try {
            $response = $app->handlePaidNotify(function ($message, $fail) {
                Log::write($message,'wx-pay-notify_message');
                $order_no_arr = explode('_',$message['out_trade_no']);
                $order_no = $order_no_arr[0];
                $other=[
                    'trade_no'=>$message['transaction_id'],
                    'pay_order_no'=>$message['out_trade_no'],
                ];
                switch ($message['attach']){
                    case 'music':
                        OrderMusicSingle::getInstance()->complete($order_no,20,$other);
                        break;
                    case 'vip':
                        OrderVipSingle::getInstance()->complete($order_no,20,$other);
                        break;
                    case 'entity':
                        OrderEntitySingle::getInstance()->complete($order_no,20,$other);
                        break;
                    case 'group':
                        $res = GroupOrderSingle::getInstance()->complete($order_no,20,$other);
                        break;
                    default:
                        break;
                }
                // 你的逻辑
                return true;
                // 或者错误消息
            });
            $response->send(); // Laravel 里请使用：return $response;
        } catch (Exception $e) {

        }
    }
    function groupRefund(){
        Log::write($this->request->param(),'wx-refund_group-notify');
        $app = WxPaySingle::getInstance()->getApp();
        $response = $app->handleRefundedNotify(function ($message, $reqInfo, $fail) {

            $order_no = $message['out_trade_no'];
            if ($message['return_code'] === 'SUCCESS' && $reqInfo['refund_status'] === 'SUCCESS') {
                //$reqInfo['out_trade_no']
                GroupOrderSingle::getInstance()->refund($order_no);
            } else {
                return $fail('通信失败，请稍后在通知我');
            }

            return true; // 返回 true 告诉微信“我已处理完成”
            // 或返回错误原因 $fail('参数格式校验错误');
        });

        $response->send();
    }
}